/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package singleton;

import entity.Users;
import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

/**
 *
 * @author antonio
 */
@Singleton
@TransactionManagement(TransactionManagementType.CONTAINER)
public class SingletonSessionScheduleProcessBean implements SingletonSessionScheduleProcessBeanLocal, TimedObject {
    
    @Resource
    private TimerService timerService;
    
    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public Date scheduleProcessing(ScheduleExpression expression, Users user) {
        if(expression == null) {
            throw new IllegalArgumentException();
        }
        TimerConfig config = new TimerConfig();
        config.setInfo(user);
        Timer timer = timerService.createCalendarTimer(expression, config);
        Date next = timer.getNextTimeout();
        return next;
    }

    @Override
    public void ejbTimeout(Timer timer) {
        Users user = (Users) timer.getInfo();
        System.out.println("Start...");
        for(int i = 0; i < 10; i++) {
            System.out.println("I'm doing something for "+user);
        }
        System.out.println("End");
        timer.cancel();
    }

}
